<?php

function deconstructMatchString($matchstring) {
    // I am sorry this is such a hack. gmm 3/13/09
    if (strstr($matchstring, "qm")) {
        // It's a qual
        $complevel = 10;
        $matchnumber = substr($matchstring, 2); //matchnumber is everything after "qm"
        return array($complevel, $matchnumber);
    }
    if (strstr($matchstring, "ef")) {
        $complevel = 20;
        $rest = substr($matchstring, 2);
        $matchnumbers = split("m", $rest);
        $matchnumber = $matchnumbers[0] * 10 + $matchnumbers[1];
        return array($complevel, $matchnumber);
    }
    if (strstr($matchstring, "qf")) {
        $complevel = 30;
        $rest = substr($matchstring, 2);
        $matchnumbers = split("m", $rest);
        $matchnumber = $matchnumbers[0] * 10 + $matchnumbers[1];
        return array($complevel, $matchnumber);
    }
    if (strstr($matchstring, "sf")) {
        $complevel = 40;
        $rest = substr($matchstring, 2);
        $matchnumbers = split("m", $rest);
        $matchnumber = $matchnumbers[0] * 10 + $matchnumbers[1];
        return array($complevel, $matchnumber);
    }
    if (strstr($matchstring, "f")) {
        $complevel = 50;
        $rest = substr($matchstring, 1);
        $matchnumbers = split("m", $rest);
        $matchnumber = $matchnumbers[0] * 10 + $matchnumbers[1];
        return array($complevel, $matchnumber);
    }
    else return False;
}

class Match {
	private $matchid;
	private $eventid;
	private $level;
	private $name;
	private $number;
	private $list_of_videos;
	private $red_teams;
	private $blue_teams;
	private $red_score;
	private $blue_score;
	
	//These are temporary and should be phased out for a video-abstracted db schema.
	private $vidpath;
	private $flvpath;
	private $thanks;
	
	// CONTRACT: __construct : number -> Match
	// PURPOSE
	// __construct is the auto-called function that builds a new Match. It takes a $matchid and returns the Match object for the corresponding match in the database.
	
	function __construct($match) {
		//ensure valid input
		if (!is_numeric($match)) {
		    
		    $match_exploded = split("_", $match);
		    $eventstr = $match_exploded[0];
		    $matchstr = $match_exploded[1];
		    list($complevel, $matchnumber) = deconstructMatchString($matchstr);
		    
		    $event = new Event($eventstr);
		    
		    $matchinfo_query_filter = "SELECT * FROM matches WHERE event='{$event->getEventID()}' AND complevel='$complevel' AND matchnumber='$matchnumber' LIMIT 1";
    		$matchinfo_query = mysql_query($matchinfo_query_filter);
    		if (mysql_num_rows($matchinfo_query) < 1) {
    			throw_error("No match found for matchid for Match Object instantiation. Given " . $match);
    		}
		} else {
    		//setup and run query
    		$matchinfo_query_filter = "SELECT * FROM matches WHERE matchid='$match' LIMIT 1";
    		$matchinfo_query = mysql_query($matchinfo_query_filter);
    		if (mysql_num_rows($matchinfo_query) < 1) {
    			throw_error("No match found for matchid for Match Object instantiation. Given " . $match);
    		}
    	}
		//copy into object
		$matchinfo = mysql_fetch_array($matchinfo_query);
		$this->matchid 		= $matchinfo["matchid"];
		$this->eventid 		= $matchinfo["event"];
		$this->complevel	= $matchinfo["complevel"];
		$this->name 		= $matchinfo["matchname"];
		$this->matchnumber 	= $matchinfo["matchnumber"];
		$this->list_of_videos = array(); //replace with function to retreive all video_ids for match.
		$this->red_teams 	= array($matchinfo["red1"], $matchinfo["red2"], $matchinfo["red3"]);
		$this->blue_teams 	= array($matchinfo["blue1"], $matchinfo["blue2"], $matchinfo["blue3"]);
		$this->red_score 	= $matchinfo["redscore"];
		$this->blue_score 	= $matchinfo["bluescore"];
		
		//These are temporary and should be phased out for a video-abstracted db schema.
		if ($matchinfo["vidup"] == 1) {
			$this->vidpath	= $this->videopath($matchinfo["vidext"]);
			$this->vidext = $matchinfo["vidext"];
		} else {
			$this->vidpath	= Null;
			$this->vidext = Null;
		}
		if ($matchinfo["flvup"] == 1) {
			$this->flvpath = $this->videopath('flv');
			$this->thumbpath = $this->videopath('jpg');
		} else {
			$this->flvpath 	= Null;
		}
		$this->thanks = $matchinfo["thanks"];
	}
	
	function getMatchID() {
		return $this->matchid;
	}
	function getRedScore() {
		return $this->red_score;
	}
	function getBlueScore() {
		return $this->blue_score;
	}
	function getEventID() {
		return $this->eventid;
	}
	function getComplevel() {
		return $this->complevel;
	}
	function getMatchNumber() {
		return $this->matchnumber;
	}
	function getVidPath() {
	    return $this->vidpath;
	}
	function getVidExt() {
	    return $this->vidext;
	}
	function getVidSize() {
	    global $BASE_PATH;
	    $video_rel_path = str_replace($BASE_PATH, "../tbatv/", $this->getVidPath());
	    if (file_exists($video_rel_path)) {
	        $size_in_bytes = filesize($video_rel_path);
    	    $size_in_megabytes = floor($size_in_bytes / 1048576);
    	    return $size_in_megabytes;
	    } else {
	        return 0;
	    }
	}
	function getFlvPath() {
	    return $this->flvpath;
	}
	function getThumbPath() {
	    return $this->thumbpath;
	}
	function getCodeString() {
	    $tba = new tbatvController();
	    $event = $this->getEvent();
	    $complevelstring = $tba->stringComplevelShort($this->getComplevel());
	    if ($this->getComplevel() > 10) {
	        $matchstring = sprintf("%dm%d", ($this->getMatchNumber() / 10), floor($this->getMatchNumber() % 10));
	    } else {
	        $matchstring = sprintf("m%d", $this->getMatchNumber()); //qual
	    }
	    return $event->getYear() . $event->getEventShort() . "_" . $complevelstring . $matchstring;
	}
	
	function getTeams($color) {
		if ($color == 'red') {
			return $this->red_teams;
		} elseif ($color == 'blue') {
			return $this->blue_teams;
		} else {
			return -1;
		}
	}
	
	// CONTRACT: getName() : null -> string
	// PURPOSE
	// getName returns a string containing the name of this particular match
	function getName() {
		//import global dictionaries
		global $complevelnames, $complevelshort, $weeknames;
		
		if ($this->complevel == 10) {
			$matchnumber_output = $this->matchnumber;
		}
		
		//elim info
		if ($this->complevel > 10) {
			$matchnumber_output = " " . floor($this->matchnumber / 10) . " Match " . ($this->matchnumber - floor($this->matchnumber / 10) * 10);
		}
		
		//correct for database storage technique. Some finals don't have the "1x" they should.
		if ($this->complevel == 50 AND $this->matchnumber < 10) $this->matchnumber+=10;
		if ($this->complevel == 50) {
			$matchnumber_output = " Match " . ($this->matchnumber-10);
		}
		
		//return match name
		return "{$complevelnames[$this->complevel]} {$matchnumber_output}";
	}
	
	// CONTRACT: getEvent() : null -> Event
	// PURPOSE
	// getEvent returns the Event Object that represents the event this match took place at.
	function getEvent() {
		return new Event($this->getEventID());
	}
	
	// CONTRACT: getWinner() : null -> string
	// PURPOSE
	// getWinner() returns the string for the alliance that won.
	function getWinner() {
		if ($this->getRedScore() > $this->getBlueScore()) {
			return 'red';
		} elseif ($this->getRedScore() < $this->getBlueScore()) {
			return 'blue';
		} elseif ($this->getRedScore() == $this->getBlueScore()) {
			return 'tie';
		}
	}
	
	// CONTRACT: getVideos() : null -> list of Videos
	// PURPOSE
	// getVideos() returns a list of Video Objects of this particular match.
	// Currently, this implementation is a crutch on the old DB schema.
	function getVideos() {
		$list_of_videos = array();
		if ($this->flvpath != Null) {
			$list_of_videos[] = new Video($this->flvpath);
		}
		if ($this->vidpath != Null) {
			$list_of_videos[] = new Video($this->vidpath);
		}
		return $list_of_videos;
	}
	
	// CONTRACT: hasVid(): null -> bool
	// Does the match have HQ Video?
	function hasVid() {
	    if ($this->vidpath != Null) {
	        return True;
	    } else {
	        return False;
	    }
	}
	// CONTRACT: hasFlv(): null -> bool
	// Does the match have FLV Video?
	function hasFlv() {
	    if ($this->flvpath != Null) {
	        return True;
	    } else {
	        return False;
	    }
	}
	// CONTRACT: hasVideo(): null -> bool
	// Does the match have ANY video?
	function hasVideo() {
		return ($this->hasVid() OR $this->hasFlv());
	}
	
	// CONTRACT: linkto() : string -> string
	// PURPOSE
	// linkto() takes (optionally) a string, and returns an HTML formatted anchor tag linking to the match's specific page.
	function linkto($string = Null) {
		global $BASE_PATH;
		global $MOD_REWRITE_ON;
		if ($string == Null) $string = $this->getName();
		if ($MOD_REWRITE_ON) {
		    return "<a href=\"" . $BASE_PATH . "match/" . $this->getCodeString() . "\">" . $string . "</a>";
		} else {
		    return "<a href=\"" . $BASE_PATH . "match.php?match=" . $this->getCodeString() . "\">" . $string . "</a>";
		}
	}
	
	// THESE ARE ARCHAIC AND SHOULD BE PHASED OUT.
	function getThanks() {
		return $this->thanks;
	}
	
	// CONTRACT: videopath() : string -> string
	// PURPOSE
	// videopath() takes an extension, and says where the video/image file for the match should be that has that extension.
	function videopath($extension) {
	    global $VIDEO_BASE_PATH;
		$event = $this->getEvent();
		$complevel = $this->getComplevel();
		$matchnumber = $this->getMatchNumber();
		
		//import global dictionaries
		global $complevelnames, $complevelshort, $weeknames;
		//truncate year from YYYY to YY
		$yearshort = str_pad($event->getYear() - 2000, 2, "0", STR_PAD_LEFT); //this will only work until 2100.
		
		//establish foldertree
		$root = $VIDEO_BASE_PATH . "vids/";
		$dir = "{$yearshort}{$event->getEventShort()}/";
		
		//correct for database storage technique. Finals don't have the "1x" they should.
		if ($complevel == 50 AND $matchnumber < 10) $matchnumber+=10;
		
		//shift match number if its an elim.
		if ($complevel > 10) {
			$setnumber = floor($matchnumber / 10);
			$matchnumber = $matchnumber - $setnumber * 10;
		}
				
		//produce filename.
		$filename = "{$event->getEventShort()}_{$complevelshort[$complevel]}{$setnumber}m{$matchnumber}.{$extension}";

		//return path and name.
		return $root . $dir . $filename;
	}
}

?>